// 防抖: 即每次执行，若在延迟时间内，则重置定时器，按最后一次执行
export function debounce(fn, delay = 300) {
  let timer = null
  return function (...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn(args)
      timer = null
    }, delay)
  }
}

//节流： 每次执行，都要等第一次执行完，再执行下一个，以第一次为准
export function throttle(fn, delay = 300) {
  let timer = null
  return function (...args) {
    if (timer) {
      return
    }
    fn(args)
    console.log('delay', delay)

    timer = setTimeout(() => {
      timer = null
    }, delay)
  }
}
// jsonp https://blog.csdn.net/MICHAEL_PRINCE/article/details/128953642
export function jsonp(url) {
  // 回调函数名
  const callbackName = 'callback'
  return new Promise((resolve) => {
    // 定义全局回调
    globalThis[callbackName] = (data) => {
      resolve(data)
    }
    // 创建script 发送jsonp请求
    const scriptDom = document.createElement('script')
    // scriptDom.type = 'text/script'

    const baseURL = import.meta.env?.VITE_BASE_URL || 'http://localhost:3000'

    scriptDom.src = `${baseURL}${url}?name=xw&cb=${callbackName}`

    document.body.appendChild(scriptDom)
    setTimeout(() => {
      document.body.removeChild(scriptDom)
    }, 500)
  })
}
